package felix.things.router.modbus.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class ConfigurationTools {

    private static final ObjectMapper mapper = new ObjectMapper();

    public static <T> T readConfiguration(JsonNode configurationNode, Class<T> clazz) throws IOException {
        try {
            return mapper.treeToValue(configurationNode, clazz);
        } catch (IOException e) {
            log.error("Failed to load {} configuration from {}", clazz, configurationNode);
            throw e;
        }
    }

    public static <T> T readFileConfiguration(String configurationFile, Class<T> clazz) throws IOException {
        try {
            return mapper.readValue(getFileAsStream(configurationFile), clazz);
        } catch (IOException e) {
            log.error("Failed to load {} configuration from {}", clazz, configurationFile);
            throw e;
        }
    }

    private static InputStream getFileAsStream(String configurationFile) {
        return ConfigurationTools.class.getClassLoader().getResourceAsStream(configurationFile);
    }
}
